<?php

namespace Xiaoc\Api;

use PhalApi\Api;

/**
 * Xiaoc普通团购商品结算
 *
 * @author: zhy <zhy302813@163.com> 2017-8-19
 */
class Shopping extends Common
{

    public function getRules()
    {
        return array(
            'orderinfo' => array(
                'token' => array('name' => 'token', 'require' => true, 'desc' => '用户Token'),
                'rec_id' => array('name' => 'rec_id', 'type' => 'array', 'format' => 'explode', 'separator' => ',', 'require' => true, 'desc' => '购物车ID(多个ID以,分割)')
            ),
            'suborder' => array(
                'token' => array('name' => 'token', 'require' => true, 'desc' => '用户Token'),
                'address_id' => array('name' => 'address_id', 'require' => true, 'desc' => '收货地址ID'),
                'postscript' => array('name' => 'postscript', 'default' => '', 'desc' => '留言'),
                'pay_id' => array('name' => 'pay_id', 'require' => true, 'desc' => '支付方式ID'),
                'use_money' => array('name' => 'use_money', 'require' => true, 'default' => 0, 'desc' => '使用余额支付（1是）'),
                'money_pwd' => array('name' => 'money_pwd', 'desc' => '余额支付密码'),
                'inv_payee' => array('name' => 'inv_payee', 'default' => '个人', 'desc' => '发票类型（个人、公司）'),
                'inv_content' => array('name' => 'inv_content', 'default' => '不开发票', 'desc' => '发票抬头'),
                'from' => array('name' => 'from', 'require' => true, 'desc' => '订单来源（app wap）'),
                'rec_id' => array('name' => 'rec_id', 'type' => 'array', 'format' => 'explode', 'separator' => ',', 'require' => true, 'desc' => '购物车ID(多个ID以,分割)')
            ),
            'dopay' => array(
                'token' => array('name' => 'token', 'require' => true, 'desc' => '用户Token'),
                'pay_sn' => array('name' => 'pay_sn', 'require' => true, 'desc' => '订单号'),
                'pay_id' => array('name' => 'pay_id', 'desc' => '支付方式ID'),
                'subject' => array('name' => 'subject', 'default' => '校园汇商城订单', 'desc' => '支付名称')
            ),
            'ordernow' => array(
                'goods_id' => array('name' => 'goods_id', 'type' => 'int', 'require' => true, 'desc' => '商品ID'),
                'token' => array('name' => 'token', 'require' => true, 'desc' => '用户Token'),
                'number' => array('name' => 'number', 'require' => true, 'default' => 1, 'desc' => '购买数量'),
                'ru_id' => array('name' => 'ru_id', 'type' => 'int', 'require' => true, 'default' => 0, 'desc' => '店铺ID'),
                'spec' => array('name' => 'spec', 'type' => 'array', 'format' => 'explode', 'separator' => ',', 'desc' => '商品规格(多个规格ID以,分割)'),
                'is_crowd' => array('name' => 'is_crowd', 'require' => true, 'default' => 0, 'desc' => '是否是众筹商品（1是）')
            )
        );
    }

    /**
     * 确认订单
     * @desc 订单提交确认页
     * @return boolean address 收货地址（存在则返回数组）
     * @return array list 商品列表
     * @return float usermoney 用户可用余额
     * @return boolean has_paypwd 是否设置支付密码
     */
    public function orderinfo()
    {
        $userinfo = $this->check_login($this->token);
        $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
        $rec_id = $this->rec_id;
        $rec_id[] = 0;

        $recid = implode(',', $rec_id);
        $where = ' and rec_id in (' . $recid . ')';
        //查询收货地址
        $data = $this->getAddress($userinfo['user_id']);

        //商品信息
        $sql = 'select c.goods_id,c.product_id,c.goods_price,c.goods_number,c.goods_attr,c.shipping_fee,g.goods_thumb,g.goods_number as stock,g.is_shipping,g.goods_name from ' .
            $prefix . 'cart as c left join ' . $prefix . 'goods as g on c.goods_id = g.goods_id  ' .
            ' where c.user_id = ' . $userinfo['user_id'] . $where . ' order by c.ru_id asc,c.rec_id desc';
        $list = \PhalApi\DI()->notorm->goods_attr->queryAll($sql, array());
        if (count($list) > 0) {
            $total_num = 0;
            $total_price = 0;
            $shipping_fee = 0;
            foreach ($list as $key => $vo) {
                $total_num += $vo['goods_number'];
                $total_price += $vo['goods_price'] * $vo['goods_number'];
                if ($vo['is_shipping'] > 0) {
                    $shipping_fee += $vo['shipping_fee'] * $vo['goods_number'];
                }
                $lists[] = $list[$key];
            }
            $nums['total_num'] = $total_num;
            $nums['total_price'] = $total_price;
            $nums['shipping_fee'] = $shipping_fee;
            $data['list'] = $lists;
            $data['nums'] = $nums;
        } else {
            return false;
        }
        //支付方式
        $payment_where['enabled'] = 1;
        $payment_where['pay_code'] = array('alipay', 'balance', 'wxpay', 'cod');
        $payment = $this->medoo->select('payment', array('pay_id', 'pay_code', 'pay_name'), $payment_where);
        $data['payment'] = $payment;
        return $data;
    }

    /**
     * 立即下单
     * @desc 立即下单
     * @return bool|mixed
     */
    public function orderNow()
    {
        $userinfo = $this->check_login($this->token);
        $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
        $rec_id = $this->rec_id;
        $rec_id[] = 0;

        $recid = implode(',', $rec_id);
        $where = ' and rec_id in (' . $recid . ')';
        //查询收货地址
        $data = $this->getAddress($userinfo['user_id']);

        //商品信息
        $sql = 'select c.goods_id,c.product_id,c.goods_price,c.goods_number,c.goods_attr,c.shipping_fee,g.goods_thumb,g.goods_number as stock,g.is_shipping,g.goods_name from ' .
            $prefix . 'cart as c left join ' . $prefix . 'goods as g on c.goods_id = g.goods_id  ' .
            ' where c.user_id = ' . $userinfo['user_id'] . $where . ' order by c.ru_id asc,c.rec_id desc';
        $list = \PhalApi\DI()->notorm->goods_attr->queryAll($sql, array());
        if (count($list) > 0) {
            $total_num = 0;
            $total_price = 0;
            $shipping_fee = 0;
            foreach ($list as $key => $vo) {
                $total_num += $vo['goods_number'];
                $total_price += $vo['goods_price'] * $vo['goods_number'];
                if ($vo['is_shipping'] > 0) {
                    $shipping_fee += $vo['shipping_fee'] * $vo['goods_number'];
                }
                $lists[] = $list[$key];
            }
            $nums['total_num'] = $total_num;
            $nums['total_price'] = $total_price;
            $nums['shipping_fee'] = $shipping_fee;
            $data['list'] = $lists;
            $data['nums'] = $nums;
        } else {
            return false;
        }
        //支付方式
        $payment_where['enabled'] = 1;
        $payment_where['pay_code'] = array('alipay', 'balance', 'wxpay', 'cod');
        $payment = $this->medoo->select('payment', array('pay_id', 'pay_code', 'pay_name'), $payment_where);
        $data['payment'] = $payment;
        return $data;
    }

    private function getAddress($user_id)
    {
        $data['address'] = \PhalApi\DI()
            ->notorm
            ->user_address
            ->select('address_id,consignee,tel,mobile,address,province,city,district')
            ->where(array('user_id' => $user_id))
            ->order('is_default , address_id desc')
            ->fetchOne();

        //用户可用余额
        $users = \PhalApi\DI()
            ->notorm
            ->users
            ->select('user_money')
            ->where(array('user_id' => $user_id))
            ->fetchOne();
        $data['usermoney'] = $users['user_money'] ? $users['user_money'] : 0;

        //支付密码是否设置
        $paypwd = \PhalApi\DI()
            ->notorm
            ->users_paypwd
            ->select('paypwd_id')
            ->where(array('user_id' => $user_id))
            ->fetchOne();
        $data['has_paypwd'] = $paypwd['paypwd_id'] ? true : false;

        if (isset($data['address']['address_id']) && $data['address']['address_id'] > 0) {
            $regid = array($data['address']['province'], $data['address']['city'], $data['address']['district']);
            $address = \PhalApi\DI()
                ->notorm
                ->region
                ->select('region_name')
                ->where('region_id', $regid)
                ->order('region_type asc')
                ->fetchAll();
            $data['address']['alladdr'] = '';
            foreach ($address as $vo) {
                $data['address']['alladdr'] .= $vo['region_name'];
            }
            $data['address']['alladdr'] .= $data['address']['address'];
        } else {
            $data['address'] = false;
        }
        return $data;
    }

    /**
     * 提交订单
     * @desc 订单生成
     * @return boolean
     */
    public function suborder()
    {
        $pay = array();
        $ord = array();
        $userinfo = $this->check_login($this->token);
        $rec_id = $this->rec_id;
        $rec_id[] = 0;
        $address_id = $this->address_id;
        //判断购物车中商品库存
        $goodslist = $this->checkstock($rec_id);
        $group = '';
        if (count($goodslist['list']) == 1 && $goodslist['list'][0]['rec_type'] == 1) {
            $group = 'group_buy';
        }
        if ($goodslist['list']) {
            $order_amount = $goodslist['count']['total_price'] + $goodslist['count']['shipping_fee'];
            $order_sn = get_order_sn();
            $surplus = 0;
            if ($this->use_money == 1) {
                //使用余额
                $users = \PhalApi\DI()
                    ->notorm
                    ->users_paypwd
                    ->select('pay_password,ec_salt')
                    ->where(array('user_id' => $userinfo['user_id']))
                    ->fetchOne();
                if (!$users) {
                    $this->api_error_msg('未设置交易密码！');
                } else {
                    $cf['ec_salt'] = $users['ec_salt'];
                    $cf['password'] = $this->money_pwd;
                    $pwd = $this->user_password($cf);
                    if ($pwd == $users['pay_password']) {
                        //用户可用余额
                        $money = \PhalApi\DI()
                            ->notorm
                            ->users
                            ->select('user_money,frozen_money')
                            ->where(array('user_id' => $userinfo['user_id']))
                            ->fetchOne();
                        if ($money['user_money'] > 0) {
                            if ($money['user_money'] < $order_amount) {
                                $upmoney = array('user_money' => 0);
                                $rs = \PhalApi\DI()->notorm->users->where('user_id', $userinfo['user_id'])->update($upmoney);
                                if ($rs) {
                                    $account['user_id'] = $userinfo['user_id'];
                                    $account['user_money'] = 0 - $money['user_money'];
                                    $account['change_time'] = gmtime();
                                    $account['change_desc'] = '支付订单 ' . $order_sn;
                                    $account['change_type'] = 99;
                                    \PhalApi\DI()->notorm->account_log->insert($account);
                                    $surplus = $money['user_money'];
                                }
                            } else {
                                $upmoney = array('user_money' => $money['user_money'] - $order_amount);
                                $rs = \PhalApi\DI()->notorm->users->where('user_id', $userinfo['user_id'])->update($upmoney);
                                if ($rs) {
                                    $account['user_id'] = $userinfo['user_id'];
                                    $account['user_money'] = 0 - $order_amount;
                                    $account['change_time'] = gmtime();
                                    $account['change_desc'] = '支付订单 ' . $order_sn;
                                    $account['change_type'] = 99;
                                    \PhalApi\DI()->notorm->account_log->insert($account);
                                    $surplus = $order_amount;
                                }
                            }
                        }
                    } else {
                        $this->api_error_msg('交易密码有误！');
                    }
                }
            }

            $address = $this->addressinfo($address_id);
            //插入订单主表
            $order['order_sn'] = $order_sn;
            $order['user_id'] = $userinfo['user_id'];
            $order['order_status'] = 1;
            $order['consignee'] = $address['consignee'];
            $order['country'] = 1;
            $order['province'] = $address['province'];
            $order['city'] = $address['city'];
            $order['district'] = $address['district'];
            $order['address'] = $address['address'];
            $order['mobile'] = $address['mobile'];
            $order['postscript'] = $this->postscript;  //订单附言
            $order['pay_id'] = $this->pay_id; //支付方式ID
            $order['inv_payee'] = $this->inv_payee; //发票抬头
            $order['inv_content'] = $this->inv_content; //发票内容
            $order['goods_amount'] = $goodslist['count']['total_price']; //商品总金额
            $order['shipping_fee'] = $goodslist['count']['shipping_fee']; //配送费用
            $order['order_amount'] = $order_amount - $surplus; //应付款金额
            $order['surplus'] = $surplus; //该订单使用余额的数量，取用户设定余额，用户可用余额，订单金额中最小者
            $order['froms'] = $this->from; //pc:电脑,mobile:手机,app:应用
            $order['add_time'] = gmtime();
            $order['confirm_time'] = gmtime();
            $order['extension_code'] = $group; //通过活动购买的商品的代号；GROUP_BUY是团购；AUCTION，是拍卖；SNATCH，夺宝奇兵；正常普通产品该处为空
            $order['pay_name'] = $this->medoo->get('payment', 'pay_name', array('pay_id' => $this->pay_id)); //支付方式名称
            $shipping_id = $this->medoo->get('seller_shopinfo', 'shipping_id', array('ru_id' => $goodslist['list'][0]['ru_id']));
            if (empty($shipping_id)) $shipping_id = 2; //圆通快递
            $order['shipping_id'] = $shipping_id;

            \PhalApi\DI()->notorm->order_info->insert($order);
            $order_id = \PhalApi\DI()->notorm->order_info->insert_id();
            if ($order_id) {

                $pay['order_name'] = '校创商城订单';
                $pay['order_money'] = $order['order_amount'];
                $pay['order_sn'] = $order_sn;

                $datas = $list = array();

                foreach ($goodslist['list'] as $vo) {
                    $arrs = array(
                        'order_id' => $order_id,
                        'goods_id' => $vo['goods_id'],
                        'goods_name' => $vo['goods_name'],
                        'goods_sn' => $vo['goods_sn'],
                        'product_id' => $vo['product_id'],
                        'goods_number' => $vo['goods_number'],
                        'market_price' => $vo['market_price'],
                        'goods_price' => $vo['goods_price'],
                        'goods_attr' => $vo['goods_attr'],
                        'goods_attr_id' => $vo['goods_attr_id'],
                        'ru_id' => $vo['ru_id'],
                        'is_real' => 1,
                        'extension_code' => $group
                    );
                    $datas[] = $arrs;
                    $list[$vo['ru_id']][] = $arrs;

                    @$ord[$vo['ru_id']]['goods_amount'] += $vo['goods_price'] * $vo['goods_number'];
                    if ($vo['is_shipping'] > 0) {
                        $ord[$vo['ru_id']]['shipping_fee'] += $vo['shipping_fee'] * $vo['goods_number'];
                    }

                    @$ord[$vo['ru_id']]['order_amount'] += $ord[$vo['ru_id']]['shipping_fee'] + $ord[$vo['ru_id']]['goods_amount'];
                }
                $order_goods = \PhalApi\DI()->notorm->order_goods->insert_multi($datas);
                if ($order_goods) {
                    //修改库存
                    $this->change_order_goods_storage($order_id, true);
                    //清空购物车
                    \PhalApi\DI()->notorm->cart->where('rec_id', $rec_id)->delete();

                    $log['order_id'] = $order_id;
                    $log['order_amount'] = $order['order_amount'];
                    $log['order_sn'] = $order['order_sn'];
                    \PhalApi\DI()->notorm->pay_log->insert($log);

                }
                $store_num = count($list);
                if ($store_num > 1) { //是否是多店铺【是则拆分订单】
                    $share = $surplus;
                    $sur = 0;
                    foreach ($list as $k => $vo) {
                        if ($share > 0) {
                            if ($ord[$k]['order_amount'] > $share) {
                                $sur = $share;
                                $share = 0;
                            } else {
                                $sur = $ord[$k]['order_amount'];
                                $share = $share - $ord[$k]['order_amount'];
                            }
                        }
                        $order['order_sn'] = get_order_sn();
                        $order['main_order_id'] = $order_id;
                        $order['goods_amount'] = $ord[$k]['goods_amount'];
                        $order['shipping_fee'] = $ord[$k]['shipping_fee'];
                        $order['surplus'] = $sur;
                        $order['order_amount'] = $ord[$k]['order_amount'] - $sur;
                        $order['shipping_id'] = $this->medoo->get('seller_shopinfo', 'shipping_id', array('ru_id' => $k));
                        \PhalApi\DI()->notorm->order_info->insert($order);
                        $ord_id = \PhalApi\DI()->notorm->order_info->insert_id();
                        if ($ord_id) {
                            foreach ($list[$k] as $ko => $vo) {
                                $list[$k][$ko]['order_id'] = $ord_id;
                            }
                            $order_goods = \PhalApi\DI()->notorm->order_goods->insert_multi($list[$k]);
                        }
                        $log['order_id'] = $ord_id;
                        $log['order_amount'] = $order['order_amount'];
                        $log['order_sn'] = $order['order_sn'];
                        \PhalApi\DI()->notorm->pay_log->insert($log);
                    }
                }
            } else {
                $this->api_error_msg('订单生成失败！');
            }
        } else {
            $this->api_error_msg('存在商品库存不足！');
        }

        return $pay;
    }

    /**
     * 订单支付
     * @desc 订单支付
     * @return boolean
     */
    public function dopay()
    {
        $name = '校创商城订单';
        $userinfo = $this->check_login($this->token);
        $orderinfo = \PhalApi\DI()
            ->notorm
            ->order_info
            ->select('order_sn,pay_id,pay_status,order_id,order_amount,main_order_id,extension_code')
            ->where(array('user_id' => $userinfo['user_id'], 'order_sn' => $this->pay_sn))
            ->fetchOne();
        if ($orderinfo) {
            if ($orderinfo['pay_status'] == 0) {
                if ($orderinfo['order_amount'] == 0) { // 订单已支付
                    $is_crowd = ($orderinfo['extension_code'] == 'group_buy') ? 1 : 0;
                    $changeOrder = $this->order_paid($orderinfo['order_id'], $orderinfo['main_order_id'], $orderinfo['order_amount'], $is_crowd);
                    if ($changeOrder) {
                        return $data['is_pay'] = 1;        //①余额支付完
                    } else {
                        $this->api_error_msg('订单状态更改失败！');
                    }
                } else {
                    if ($this->pay_id && $orderinfo['pay_id'] != $this->pay_id) {
                        $payment = $this->paymentinfo($this->pay_id);
                        if ($payment) {
                            \PhalApi\DI()->notorm->order_info->where('order_id', $orderinfo['order_id'])->update(array('pay_id' => $this->pay_id));
                        }
                    } else {
                        $payment = $this->paymentinfo($orderinfo['pay_id']);
                    }
                    if ($payment) {
                        $payconfig = unserialize($payment['pay_config']);

                        if ($payment['pay_code'] == 'alipay') {

                            $config['app_id'] = $payconfig[2]['value'];
                            $config['notify_url'] = 'http://' . $_SERVER['HTTP_HOST'] . '/Xiaoc/Shopping/alipaycallback';
                            $alipay = new \Alipay_Lite($config);
                            $result['str'] = $alipay->DoPay($orderinfo['order_sn'], $orderinfo['order_amount'], $name);
                            $result['is_pay'] = 0;
                            $result['pay_code'] = 'alipay';
                            return $result;

                        } elseif ($payment['pay_code'] == 'wxpay') {
                            $config['APPID'] = '';
                            $config['KEY'] = '';
                            $config['MCHID'] = '';
                            $config['ATTACH'] = '';
                            $config['BACkURL'] = 'http://' . $_SERVER['HTTP_HOST'] . '/Xiaoc/Shopping/wxpaycallback';
                            $wxpay = new \Wxpay_Lite($config);
                            $res = $wxpay->AppPay($name, $orderinfo['order_amount'], $orderinfo['order_sn']);
                            if ($res['status']) {
                                $result['str'] = $res['data'];
                            } else {
                                $result['str'] = $res;
                            }
                            $result['is_pay'] = 0;
                            $result['pay_code'] = 'wxpay';
                            return $result;

                        }
                        return $data['is_pay'] = 2;  //②货到付款
                    } else {
                        $this->api_error_msg('支付方式有误！');
                    }
                }

            } else {
                $this->api_error_msg('该订单已支付！');
            }
        } else {
            $this->api_error_msg('订单号有误！');
        }
    }

    /**
     * 支付宝支付回调
     * @return boolean
     */
    public function alipaycallback()
    {
        $param = $_REQUEST;
        if ($param['trade_status'] == 'TRADE_FINISHED' || $param['trade_status'] == 'TRADE_SUCCESS') {
            echo 'SUCCESS';
            $order_sn = $param['out_trade_no'];
            $orderinfo = \PhalApi\DI()
                ->notorm
                ->order_info
                ->select('pay_id,order_id,order_amount,main_order_id,extension_code')
                ->where(array('order_sn' => $order_sn, 'pay_status' => 0))
                ->fetchOne();
            $is_crowd = ($orderinfo['extension_code'] == 'group_buy') ? 1 : 0;
            $changeOrder = $this->order_paid($orderinfo['order_id'], $orderinfo['main_order_id'], $orderinfo['order_amount'], $is_crowd);
            if ($changeOrder) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 微信支付回调
     * @return boolean
     */
    public function wxpaycallback()
    {

        $pay_config = \PhalApi\DI()
            ->notorm
            ->payment
            ->select('pay_id, pay_code, pay_name, pay_fee, pay_desc, pay_config, is_cod')
            ->where(array('enabled' => 1, 'pay_code' => 'wxpay'))
            ->fetchOne();
        $payconfig = unserialize($pay_config['pay_config']);

        $config['APPID'] = $payconfig[0]['value'];
        $config['KEY'] = $payconfig[2]['value'];
        $config['MCHID'] = $payconfig[3]['value'];

        $wxpay = new \Wxpay_Lite($config);

        $param = $wxpay->FromXml(file_get_contents('php://input'));
        if ($param['return_code'] == 'SUCCESS' && $param['transaction_id'] && $param['result_code'] == 'SUCCESS') {
            echo $wxpay->BuidXml(array('return_code' => 'SUCCESS', 'return_msg' => 'OK'));
            $order_sn = $param['out_trade_no'];
            $orderinfo = \PhalApi\DI()
                ->notorm
                ->order_info
                ->select('pay_id,order_id,order_amount,main_order_id,extension_code')
                ->where(array('order_sn' => $order_sn, 'pay_status' => 0))
                ->fetchOne();
            $is_crowd = ($orderinfo['extension_code'] == 'group_buy') ? 1 : 0;
            $changeOrder = $this->order_paid($orderinfo['order_id'], $orderinfo['main_order_id'], $orderinfo['order_amount'], $is_crowd);
            if ($changeOrder) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 已支付订单状态修改
     */
    private function order_paid($order_id, $main_order_id = 0, $order_amount = 0, $is_crowd = 0)
    {
        $prefix = \PhalApi\DI()->config->get('dbs.tables.__default__.prefix');
        if ($order_id > 0) {
            $pay_log = \PhalApi\DI()
                ->notorm
                ->pay_log
                ->select('log_id')
                ->where(array('order_id' => $order_id, 'is_paid' => 0))
                ->fetchOne();
            if ($pay_log) {
                \PhalApi\DI()->notorm->pay_log->where('log_id', $pay_log['log_id'])->update(array('is_paid' => 1));
                $data['order_status'] = 1;
                $data['confirm_time'] = gmtime();
                $data['pay_status'] = 2;
                $data['pay_time'] = gmtime();
                $data['order_amount'] = 0;
                $data['money_paid'] = new \NotORM_Literal('money_paid + ' . $order_amount);
                $uporder = \PhalApi\DI()->notorm->order_info->where('order_id', $order_id)->update($data);
                if ($uporder) {   //订单日志
                    $log['order_id'] = $order_id;
                    $log['action_user'] = '买家';
                    $log['order_status'] = 1;
                    $log['pay_status'] = 2;
                    $log['action_note'] = '用户支付订单';
                    $log['log_time'] = gmtime();
                    \PhalApi\DI()->notorm->order_action->insert($log);
                }
                if ($uporder) {

                    if ($is_crowd == 1) {
                        $order_goods = \PhalApi\DI()
                            ->notorm
                            ->order_goods
                            ->select('goods_id,product_id')
                            ->where(array('order_id' => $order_id))
                            ->fetchOne();
                        $crowd = \PhalApi\DI()
                            ->notorm
                            ->goods_activity
                            ->select('act_id,ext_info,start_time,end_time,goods_id')
                            ->where(array('review_status' => 3, 'start_time < ?' => gmtime(), 'end_time > ?' => gmtime(), 'act_type' => 1, 'goods_id' => $order_goods['goods_id']))
                            ->order('act_id desc')
                            ->fetchOne();
                        $crowdinfo = unserialize($crowd['ext_info']);
                        if ($crowdinfo['restrict_amount'] > 0) {
                            $sql = "select SUM(og.goods_number) as goods_number from "
                                . $prefix . "order_info as oi left join "
                                . $prefix . "order_goods as og on oi.order_id = og.order_id "
                                . "where og.goods_id = " . $crowd['goods_id'] . "  and oi.extension_code ='group_buy' and oi.add_time > " . $crowd['start_time'] . " and oi.add_time < " . $crowd['end_time']
                                . " group by og.goods_id";
                            $rows = \PhalApi\DI()->notorm->order_info->queryAll($sql, array());
                            $join = isset($rows[0]['goods_number']) ? $rows[0]['goods_number'] : 0;
                            if ($join > $crowdinfo['restrict_amount'] || $join == $crowdinfo['restrict_amount']) {
                                \PhalApi\DI()->notorm->goods_activity->where('act_id', $crowd['act_id'])->update(array('is_finished' => 2, 'end_time' => gmtime()));
                            }
                        }
                    }

                    if ($main_order_id > 0) { //子订单
                        $orderinfo = \PhalApi\DI()
                            ->notorm
                            ->order_info
                            ->select('pay_status,order_amount')
                            ->where(array('order_id' => $main_order_id))
                            ->fetchOne();
                        $pom = $orderinfo['order_amount'] - $order_amount;
                        if ($pom > 0) {
                            $pdata['order_amount'] = $pom;
                            $pdata['money_paid'] = new \NotORM_Literal('money_paid + ' . $order_amount);
                        } else {
                            $pdata['order_status'] = 1;
                            $pdata['confirm_time'] = gmtime();
                            $pdata['pay_status'] = 2;
                            $pdata['pay_time'] = gmtime();
                            $pdata['order_amount'] = 0;
                            $pdata['money_paid'] = new \NotORM_Literal('money_paid + ' . $order_amount);

                            \PhalApi\DI()->notorm->pay_log->where('order_id', $main_order_id)->update(array('is_paid' => 1));
                        }
                        \PhalApi\DI()->notorm->order_info->where('order_id', $main_order_id)->update($pdata);

                    } else {
                        $orderlist = \PhalApi\DI()
                            ->notorm
                            ->order_info
                            ->select('pay_status,order_amount,order_id')
                            ->where(array('main_order_id' => $main_order_id))
                            ->fetchAll();
                        if ($orderlist) {
                            foreach ($orderlist as $vo) {
                                $sdata['order_status'] = 1;
                                $sdata['confirm_time'] = gmtime();
                                $sdata['pay_status'] = 2;
                                $sdata['pay_time'] = gmtime();
                                $sdata['order_amount'] = 0;
                                $sdata['money_paid'] = new \NotORM_Literal('money_paid + ' . $vo['order_amount']);

                                \PhalApi\DI()->notorm->order_info->where('order_id', $vo['order_id'])->update($sdata);

                                \PhalApi\DI()->notorm->pay_log->where('order_id', $vo['order_id'])->update(array('is_paid' => 1));
                            }
                        }
                    }
                    return true;
                } else {
                    return false;
                }
            }
        } else {
            return false;
        }
        return true;
    }

    private function addressinfo($address_id = 0)
    {
        $address = \PhalApi\DI()
            ->notorm
            ->user_address
            ->select('address_id,consignee,tel,mobile,address,province,city,district')
            ->where(array('address_id' => $address_id))
            ->fetchOne();
        return $address;
    }

    private function checkstock($rec_id = array())
    {
        $list = \PhalApi\DI()
            ->notorm
            ->cart
            ->select('is_shipping,user_id,goods_id,goods_sn,product_id,goods_name,market_price,goods_price,goods_number,goods_attr,rec_type,ru_id,goods_attr_id,shipping_fee')
            ->where('rec_id', $rec_id)
            ->order('rec_id desc')
            ->fetchAll();
        $total_price = $shipping_fee = 0;
        foreach ($list as $vo) {
            if ($vo['product_id'] > 0) {
                $product = \PhalApi\DI()
                    ->notorm
                    ->products
                    ->select('product_number')
                    ->where(array('product_id' => $vo['product_id']))
                    ->fetchOne();
                if ($product['product_number'] < $vo['goods_number']) {
                    return false;
                }
            } else {
                $goods = \PhalApi\DI()
                    ->notorm
                    ->goods
                    ->select('goods_number')
                    ->where(array('goods_id' => $vo['goods_id']))
                    ->fetchOne();
                if ($goods['goods_number'] < $vo['goods_number']) {
                    return false;
                }
            }
            $total_price += $vo['goods_price'] * $vo['goods_number'];
            if ($vo['is_shipping'] > 0) {
                $shipping_fee += $vo['shipping_fee'] * $vo['goods_number'];
            }
        }
        $count['total_price'] = $total_price;
        $count['shipping_fee'] = $shipping_fee;
        return array('list' => $list, 'count' => $count);
    }
}
